/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#include "imageknife_node_internal.h"
#include "border_option_napi.h"
#include "imageknife_node_animator.h"
#include "option/imageknife_option_napi.h"
#include "request/imageknife_request_internal.h"
#include "imageknife_node_image.h"
#include "imageknife_internal.h"
#include "downsampling/down_sampler.h"
#include <window_manager/oh_display_manager.h>

namespace ImageKnifePro {

// static 在主线程中执行
std::shared_ptr<ImageKnifeNode> ImageKnifeNode::CreateImageKnifeNode(std::shared_ptr<ImageKnifeOption> option)
{
    auto imageNode = std::make_shared<ImageKnifeNodeImage>(option);
    ImageKnifeInternal::GetInstance().SetImageNode(imageNode);
    return imageNode;
}

// static 在主线程中执行
std::shared_ptr<ImageKnifeNode> ImageKnifeNode::CreateImageKnifeNodeAnimator(std::shared_ptr<ImageKnifeOption> option,
    std::shared_ptr<AnimatorOption> animatorOption)
{
    auto imageNode = std::make_shared<ImageKnifeNodeAnimator>(option, animatorOption);
    ImageKnifeInternal::GetInstance().SetImageNode(imageNode);
    return imageNode;
}

// static
void ImageKnifeNodeInternal::OnNodeEvent(ArkUI_NodeEvent *event)
{
    auto nodeHandle = OH_ArkUI_NodeEvent_GetNodeHandle(event);
    ImageKnifeNodeInternal *node = reinterpret_cast<ImageKnifeNodeInternal *>(GetNodeAPI()->getUserData(nodeHandle));
    auto eventType = OH_ArkUI_NodeEvent_GetEventType(event);

    switch (eventType) {
        case NODE_EVENT_ON_AREA_CHANGE:
            node->OnAreaChange(event);
            break;
        default:
            node->OnDerivedNodeEvent(event);
            return;
    }
}

void ImageKnifeNodeInternal::OnAreaChange(ArkUI_NodeEvent *event)
{
    enum ComponentEventDataIndex {
        OLD_WIDTH_INDEX = 0,
        OLD_HEIGHT_INDEX = 1,
        WIDTH_INDEX = 6,
        HEIGHT_INDEX = 7,
    };

    auto componetEvent = OH_ArkUI_NodeEvent_GetNodeComponentEvent(event);
    width_ = componetEvent->data[WIDTH_INDEX].f32;
    height_ = componetEvent->data[HEIGHT_INDEX].f32;
    if ((width_ != componetEvent->data[OLD_WIDTH_INDEX].f32) ||
        (height_ != componetEvent->data[OLD_HEIGHT_INDEX].f32)) {
        imageKnifeRequest_->SetComponentSize(GetComponentSize());
        ImageKnifeInternal::GetInstance().Execute(imageKnifeRequest_);
    }
}

void ImageKnifeNodeInternal::RemoveBorder()
{
    GetNodeAPI()->resetAttribute(handle, NODE_BORDER_WIDTH);
    GetNodeAPI()->resetAttribute(handle, NODE_BORDER_WIDTH_PERCENT);
    GetNodeAPI()->resetAttribute(handle, NODE_BORDER_RADIUS);
    GetNodeAPI()->resetAttribute(handle, NODE_BORDER_RADIUS_PERCENT);
    GetNodeAPI()->resetAttribute(handle, NODE_BORDER_STYLE);
    GetNodeAPI()->resetAttribute(handle, NODE_BORDER_COLOR);
}

void ImageKnifeNodeInternal::SetBorder()
{
    if (border_ == nullptr) {
        // 移除旧的border设置
        RemoveBorder();
        return;
    }

    if (!border_->width.empty()) {
        SetBorderProperty(border_->width, NODE_BORDER_WIDTH);
    } else {
        // 如果percentageWidth为空，则width都为空，设置为空符合效果，两者本是一体
        SetBorderProperty(border_->percentageWidth, NODE_BORDER_WIDTH_PERCENT);
    }

    if (!border_->radius.empty()) {
        SetBorderProperty(border_->radius, NODE_BORDER_RADIUS);
    } else {
        // 如果percentageRadius为空，则radius都为空，设置为空符合效果，两者本是一体
        SetBorderProperty(border_->percentageRadius, NODE_BORDER_RADIUS_PERCENT);
    }

    SetBorderProperty(border_->color, NODE_BORDER_COLOR);
    SetBorderProperty(border_->style, NODE_BORDER_STYLE);
}

void ImageKnifeNodeInternal::Update(std::shared_ptr<ImageKnifeOption> option)
{
    IMAGE_KNIFE_CHECK(imageKnifeRequest_ == nullptr);
    if ((imageKnifeRequest_->GetStatus() != ImageKnifeRequest::Status::COMPLETE &&
        imageKnifeRequest_->GetStatus() != ImageKnifeRequest::Status::PROGRESS) || nodeState_ == CLEARED) {
        // 之前的加载请求失败或取消， 或组件复用导致图片清空， 需重置key进行重新加载
        mainSrcKey_ = "";
    } else if (!IsUpdateNecessary(option)) {
        // 图片无需加载，但border等属性可能需要更新
        UpdateAttribute(option);
        return;
    }

    Clear();
    Reuse();
    ImageKnife::GetInstance().CancelRequest(imageKnifeRequest_);
    auto request = std::make_shared<ImageKnifeRequestInternal>(option, GetNodeVersion());
    request->SetComponentId(componentId_);
    request->SetComponentSize(GetComponentSize());
    imageKnifeRequest_ = request;
    UpdateDerivedNodeEvent(option);

    border_ = option->border;
    objectFit_ = option->objectFit;
    placeholderObjectFit_ = option->placeholderObjectFit;
    errorObjectFit_ = option->errorObjectFit;
    colorFilter_ = option->colorFilter;
    SetBorder();
    ImageKnifeInternal::GetInstance().Execute(imageKnifeRequest_);
}

void ImageKnifeNodeInternal::DisposeNode()
{
    ImageKnifeInternal::GetInstance().CancelRequest(imageKnifeRequest_);
    ImageKnifeInternal::GetInstance().DisposeImageNode(componentId_);
}

void ImageKnifeNodeInternal::SyncLoad(bool syncLoad)
{
    IMAGE_KNIFE_CHECK(imageKnifeRequest_ == nullptr);
    imageKnifeRequest_->SyncLoad(syncLoad);
}

void ImageKnifeNodeInternal::SetWidth(float width)
{
    ArkUI_NumberValue value = {.f32 = width};
    ArkUI_AttributeItem item = {&value, 1};
    GetNodeAPI()->setAttribute(handle, NODE_WIDTH, &item);
}

void ImageKnifeNodeInternal::SetPercentWidth(float percent)
{
    ArkUI_NumberValue value = {.f32 = percent};
    ArkUI_AttributeItem item = {&value, 1};
    GetNodeAPI()->setAttribute(handle, NODE_WIDTH_PERCENT, &item);
}

void ImageKnifeNodeInternal::SetHeight(float height)
{
    ArkUI_NumberValue value = {.f32 = height};
    ArkUI_AttributeItem item = {&value, 1};
    GetNodeAPI()->setAttribute(handle, NODE_HEIGHT, &item);
}

void ImageKnifeNodeInternal::SetPercentHeight(float percent)
{
    ArkUI_NumberValue value = {.f32 = percent};
    ArkUI_AttributeItem item = {&value, 1};
    GetNodeAPI()->setAttribute(handle, NODE_HEIGHT_PERCENT, &item);
}

void ImageKnifeNodeInternal::SetMainSrcKey(std::string key)
{
    mainSrcKey_ = key;
}

Image_Size ImageKnifeNodeInternal::GetComponentSize()
{
    struct DisplayDensity {
        float pixels = 0;
        DisplayDensity()
        {
            auto errorCode = OH_NativeDisplayManager_GetDefaultDisplayDensityPixels(&pixels);
            if (errorCode != DISPLAY_MANAGER_OK) {
                IMAGE_KNIFE_LOG(LOG_ERROR, "GET Display Density Pixels Failed, %{public}d", errorCode);
                pixels = 0;
            }
        }
    };
    static DisplayDensity displayDensity;

    // vp to px
    return {static_cast<uint32_t>(std::round(width_ * displayDensity.pixels)),
            static_cast<uint32_t>(std::round(height_ * displayDensity.pixels))};
}

bool ImageKnifeNodeInternal::IsUpdateNecessary(std::shared_ptr<ImageKnifeOption> option)
{
    IMAGE_KNIFE_CHECK_RETURN(option == nullptr, false, "Null ImageKnifeOption");
    if (option->loadSrc.GetType() == DataType::UNDEFINED) {
        IMAGE_KNIFE_LOG(LOG_ERROR, "[ID:%{public}s] Main Source Not Set", componentId_.c_str());
        return false;
    }

    CacheKeyGenerator::MemoryKeyParams params = {.imageSource = &option->loadSrc, .type = ImageRequestType::MAIN_SRC,
                                                 .signature = option->signature, .isAnimator = IsAnimator()};
    if (option->multiTransformation != nullptr) {
        params.transformationInfo = option->multiTransformation->GetTransformInfo();
    } else if (option->transformation != nullptr) {
        params.transformationInfo = option->transformation->GetTransformInfo();
    }

    if (option->context.config != nullptr) {
        params.colorMode = option->context.config->colorMode;
    }

    params.downSamplingInfo = DownSampler::GetDownSamplingInfo(GetComponentSize(), option->downSampling);
    auto generator = ImageKnifeInternal::GetInstance().GetCacheKeyGenerator();
    IMAGE_KNIFE_CHECK_RETURN(generator == nullptr, false);

    std::string key = generator->GenerateMemoryKey(params);
    if (key != mainSrcKey_) {
        mainSrcKey_ = key;
        return true;
    }

    IMAGE_KNIFE_LOG(LOG_DEBUG, "[ID:%{public}s] Main Source not change, Update Is Unnecessary", componentId_.c_str());
    return false;
}

std::string ImageKnifeNodeInternal::GetMainSrcKey() const
{
    return mainSrcKey_;
}

void ImageKnifeNodeInternal::UpdateAttribute(std::shared_ptr<ImageKnifeOption> option)
{
    IMAGE_KNIFE_CHECK(option == nullptr);
    IMAGE_KNIFE_CHECK(imageKnifeRequest_ == nullptr);

    // 图片加载已经完成， 属性变更需要立即设置
    bool applyNow = imageKnifeRequest_->GetStatus() == ImageKnifeRequest::Status::COMPLETE;

    if (option->objectFit != objectFit_) {
        objectFit_ = option->objectFit;
        if (applyNow) {
            FitImage(option->objectFit);
        }
    }

    placeholderObjectFit_ = option->placeholderObjectFit;
    errorObjectFit_ = option->errorObjectFit;

    if (option->colorFilter != nullptr && colorFilter_ != option->colorFilter) {
        colorFilter_ = option->colorFilter;
        if (applyNow) {
            SetColorFilter(option->colorFilter->GetColorFilter());
        }
    } else if (colorFilter_ != nullptr) {
        // 当前取消colorFilter, 但之前设置了colorFilter
        colorFilter_ = nullptr;
        if (applyNow) {
            RemoveColorFilter();
        }
    }

    // 非图片组件属性，通用属性更新
    if (IsBorderChanged(option)) {
        border_ = option->border;
        SetBorder();
        if (applyNow)  {
            //  border更新需要刷新图片资源
            RefreshImage();
        }
    }
}

bool ImageKnifeNodeInternal::IsBorderChanged(std::shared_ptr<ImageKnifeOption> option)
{
    if (option->border != nullptr) {
        if (border_ == nullptr) {
            return true;
        } else if (!CompareBorderProperty(option->border->width, border_->width) ||
                   !CompareBorderProperty(option->border->percentageWidth, border_->percentageWidth) ||
                   !CompareBorderProperty(option->border->radius, border_->radius) ||
                   !CompareBorderProperty(option->border->percentageRadius, border_->percentageRadius) ||
                   !CompareBorderProperty(option->border->style, border_->style) ||
                   !CompareBorderProperty(option->border->color, border_->color)) {
            // 任意border属性发生变更
            return true;
        }
    } else if (border_ != nullptr) {
        return true;
    }

    return false;
}

void ImageKnifeNodeInternal::ApplyAttribute(ImageRequestType type)
{
    if (type == ImageRequestType::MAIN_SRC) {
        FitImage(objectFit_);
    } else if (type == ImageRequestType::PLACE_SRC) {
        FitImage(placeholderObjectFit_);
    } else {
        FitImage(errorObjectFit_);
    }

    if (colorFilter_ != nullptr && type == ImageRequestType::MAIN_SRC) {
        SetColorFilter(colorFilter_->GetColorFilter());
    } else {
        RemoveColorFilter();
    }
}
} // end of namespace